package org.goyo.main.services.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.utils.JSONUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
	private String accessDeniedUrl;
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException, ServletException {
		boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
		if (isAjax) {
			AjaxResult result = AjaxResult.resultFail("你没有相关权限,请联系管理员", null);
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(JSONUtil.obj2Json(result));
		} else {
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://" + request.getServerName() + ":"
								+ request.getServerPort() + path + "/";
			response.sendRedirect(basePath + accessDeniedUrl);
		}
	}

	public String getAccessDeniedUrl() {
		return accessDeniedUrl;
	}

	public void setAccessDeniedUrl(String accessDeniedUrl) {
		this.accessDeniedUrl = accessDeniedUrl;
	}

}
